#include <iostream>
#include <cstring>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>

// ./udpclient 127.0.0.1 8888
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        std::cerr << "Usage: " << argv[0] << " server_ip server_port" << std::endl;
        exit(0);
    }

    std::string serverip = argv[1];
    uint16_t serverport = std::stoi(argv[2]);

    // 1.创建套接字
    int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (sockfd < 0)
    {
        std::cout << "socket failed!" << std::endl;
        exit(1);
    }

    // 2.发信息
    // 要知道服务端的Ip和端口号
    struct sockaddr_in server;
    memset(&server, 0, sizeof(server));
    socklen_t len = sizeof(server);
    server.sin_family = AF_INET;
    server.sin_port = htons(serverport);
    server.sin_addr.s_addr = inet_addr(serverip.c_str());
    
    while (1)
    {
        std::string line;
        std::cout << "Please Enter# " << std::endl;
        std::getline(std::cin, line);

        // 把信息发给服务端
        int n = sendto(sockfd, line.c_str(), line.size(), 0, (struct sockaddr *)&server, len);
        if (n > 0)
        {
            // std::cout << "[clinet say#] " << line << std::endl;

            struct sockaddr_in tmp;
            socklen_t len = sizeof(tmp);
            char buffer[1024];
            // 接收服务端返回的信息
            int m = recvfrom(sockfd, buffer, sizeof(buffer) - 1, 0, (struct sockaddr *)&tmp, &len);
            if (m > 0)
            {
                buffer[m] = 0;
                std::cout << "服务端返回给客户端的: " << buffer << std::endl;
            }
            else
            {
                std::cout << "recvfrom failed!" << std::endl;
                break;
            }
        }
        else
        {
            std::cout << "sendto failed!" << std::endl;
            break;
        }
    }

    return 0;
}